<template>
  <el-container>
    <el-main class="p-0">
      <div class="mb-3">
        <query-form :params="params" @search="handleSearch" @reset="handleReset">
          <query-item label='产品名称/描述' name="keyword"></query-item>
          <query-item :label="$t('user.created')" name="Q_GE_@userExt-created_DateTime,Q_LE_@userExt-created_DateTime" type="datetime"></query-item>
          <query-item :label="$t('user.status')" name="Q_In_status_Int" :options="[0, 1, 2, 3].map((item) => ({ label: $t(`user.status.${item}`), value: item }))"></query-item>
        </query-form>
      </div>
      <div>
        <el-button type="primary" :icon="Plus" :disabled="perm('product:create')" @click="handleAdd">{{ $t('add')}}</el-button>
        <el-popconfirm :title="$t('confirmDelete')" @confirm="handleDelete(selection.map((row) => row.id))">
          <template #reference>
            <el-button :disabled="selection.length <= 0 || perm('product:delete')" :icon="Delete" class="ml-2">{{ $t('delete') }}</el-button>
          </template>
        </el-popconfirm>
        <column-setting name="user" class="ml-2" />
      </div>
      <div class="app-block mt-3">
        <el-table
          ref="table"
          v-loading="loading"
          :data="data"
          @selection-change="(rows) => (selection = rows)"
          @row-dblclick="(row) => handleEdit(row.id)"
          @sort-change="handleSort"
        >
          <column-list name="user">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column property="id" label="ID" width="64" sortable="custom"></el-table-column>
            <el-table-column property="productName" :label="$t('产品名称')" sortable="custom" min-width="100"></el-table-column>
            <el-table-column property="desc" label='描述' sortable="custom" min-width="100" show-overflow-tooltip></el-table-column>
            <el-table-column property="createDate" label='创建时间' sortable="custom" min-width="100" show-overflow-tooltip></el-table-column>
            <el-table-column property="status" :label="$t('user.status')" sortable="custom" show-overflow-tooltip>
              <template #default="{ row }">
                <el-tag v-if="row.status === 0" type="info" size="small">隐藏</el-tag>
                <el-tag v-else-if="row.status === 1" type="success" size="small">显示</el-tag>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.action')" min-width="120">
              <template #default="{ row }">
                <el-button type="primary" @click="handleEdit(row.id)" :disabled="perm('product:update')" size="small" link>{{ $t('edit') }}</el-button>
                <el-button type="primary" @click="handlePermissionEdit(row.id)" :disabled="perm('product:versionUpdate')" size="small" link>
                  版本信息
                </el-button>
                <el-button type="primary" @click="handleWorkerEdit(row.id)" :disabled="perm('product:workerList')" size="small" link>
                  维护人员
                </el-button>
                <!-- <el-popconfirm :title="$t('confirmDelete')" @confirm="handleDelete([row.id])">
                  <template #reference>
                    <el-button type="primary" :disabled="perm('user:update')" size="small" link>{{ $t('delete') }}</el-button>
                  </template>
                </el-popconfirm> -->
              </template>
            </el-table-column>
          </column-list>
        </el-table>
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:pageSize="pageSize"
          :total="total"
          :page-sizes="pageSizes"
          :layout="pageLayout"
          @size-change="fetchData()"
          @current-change="fetchData()"
          small
          background
          class="px-3 py-2 justify-end"
        ></el-pagination>
      </div>
      <product-form v-model="formVisible" :beanId="beanId" :beanIds="beanIds" :org="org" :showGlobalData="showGlobalData" @finished="fetchData" />
      <el-dialog
        v-model="dialogVisible"
        title="版本列表"
        width="68%"
      >
        <el-button type="primary" @click="versionAdd" :disabled="perm('product:versionCreate')">新增</el-button>
        <el-table
          ref="table"
          v-loading="loading"
          :data="datav"
          @selection-change="(rows) => (selection = rows)"
          @row-dblclick="(row) => handleEdit(row.id)"
          @sort-change="handleSort"
          class="mt-3 shadow bg-white"
        >
          <column-list name="role">
            <el-table-column property="id" label="ID" width="64" sortable="custom"></el-table-column>
            <el-table-column property="version" label="版本名称" sortable="custom" show-overflow-tooltip></el-table-column>
            <el-table-column property="desc" label="版本描述" sortable="custom" show-overflow-tooltip></el-table-column>
            
            <el-table-column property="status" label="状态" sortable="custom">
              <template #default="{ row }">
                <el-tag v-if="row.status === 1" size="small">显示</el-tag>
                <el-tag v-else-if="row.status === 0" type="warning" size="small">隐藏</el-tag>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.action')" width="160">
              <template #default="{ row }">
                <el-button type="primary" @click="versionEdit(row)" :disabled="perm('product:versionUpdate')" size="small" link>编辑</el-button>
                <el-button type="warning" @click="versionDelete(row.id)" :disabled="perm('product:versionDelete')" size="small" link>删除</el-button>
              </template>
            </el-table-column>
          </column-list>
        </el-table>
      </el-dialog>
      <el-dialog
        v-model="versionVisible"
        :title="versionTitle"
        width="48%"
      >
      <el-form>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="version"
              label="版本名称"
            >
              <el-input v-model="values.version" ref="focus" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status" label="显示状态">
              <el-radio-group v-model="values.status">
                <el-radio :label="1">显示</el-radio>
                <el-radio :label="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="desc" label="版本描述">
              <el-input v-model="values.desc" type="textarea" :rows="3" maxlength="2000"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="versionVisible = false">取消</el-button>
            <el-button type="primary" @click="versionConfirm"
              >确认</el-button
            >
          </span>
        </template>
      </el-dialog>
      <!-- 维护人员 -->
      <el-dialog
        v-model="workerVisible"
        title="维护人员"
        width="68%"
      >
        <el-button type="primary" @click="workerAdd" :disabled="perm('product:workerCreate')">新增</el-button>
        <el-table
          ref="tablew"
          v-loading="loading"
          :data="dataw"
          @selection-change="(rows) => (selection = rows)"
          @row-dblclick="(row) => handleEdit(row.id)"
          @sort-change="handleSort"
          class="mt-3 shadow bg-white"
        >
          <column-list name="role">
            <el-table-column property="id" label="ID" width="64" sortable="custom"></el-table-column>
            <el-table-column property="name" label="名称" sortable="custom" show-overflow-tooltip></el-table-column>
            <el-table-column property="email" label="邮箱" sortable="custom" show-overflow-tooltip></el-table-column>
            <el-table-column property="mobile" label="手机号" sortable="custom">
            </el-table-column>
            <el-table-column :label="$t('table.action')" width="160">
              <template #default="{ row }">
                <el-button type="warning" @click="workerDelete(row.id)" :disabled="perm('product:workerDelete')" size="small" link>删除</el-button>
              </template>
            </el-table-column>
          </column-list>
        </el-table>
      </el-dialog>
      <el-dialog
        v-model="workerEditVisible"
        title="新增维护人员"
        width="48%"
      >
      <el-form>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="name"
              label="人员名称"
            >
              <el-input v-model="workerForm.name" ref="focus" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="email"
              label="邮件"
            >
              <el-input v-model="workerForm.email" ref="focus" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="mobile"
              label="手机"
            >
              <el-input v-model="workerForm.mobile" ref="focus" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="workerEditVisible = false">取消</el-button>
            <el-button type="primary" @click="workerConfirm"
              >确认</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script lang="ts">
export default { name: 'UserList' };
</script>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Delete, ArrowDown } from '@element-plus/icons-vue';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import { currentUser, perm } from '@/store/useCurrentUser';
import { pageSizes, pageLayout, toParams, resetParams } from '@/utils/common';
import { toTree } from '@/utils/tree';
import { deleteUser, updateUserStatus, queryUserList, queryOrgList } from '@/api/user';
import { queryProductList, deleteProduct, productVersionList, 
createProductVersion, updateProductVersion, deleteProductVersion, 
queryProductWorker, deleteProductWorker, createProductWorker } from '@/api/product'
import { ColumnList, ColumnSetting } from '@/components/TableList';
import { QueryForm, QueryItem } from '@/components/QueryForm';
import ProductForm from './ProductForm.vue';
import VersionForm from './VersionForm.vue'
// import UserPermissionForm from './UserPermissionForm.vue';

const { t } = useI18n();
const params = ref<any>({});
const sort = ref<any>();
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const total = ref<number>(0);
const table = ref<any>();
const data = ref<Array<any>>([]);
const selection = ref<Array<any>>([]);
const loading = ref<boolean>(false);
const formVisible = ref<boolean>(false);
//版本
const dialogVisible = ref<boolean>(false);
const versionVisible = ref<boolean>(false);
const values = ref<any>({});
const datav = ref<Array<any>>([]);
const versionTitle = ref<string>('');
const beanId = ref<number>();
const beanIds = computed(() => data.value.map((row) => row.id));
const dialogs = ref<any>(null)
const showGlobalData = ref<boolean>(false);
const orgTreeLoading = ref<boolean>(false);
const orgTree = ref<any>();
const orgTreeData = ref<any[]>([]);
const org = ref<any>();

const deletable = (bean: any) => bean.id > 1 && currentUser.rank <= bean.rank;

const fetchOrg = async () => {
  orgTreeLoading.value = true;
  try {
    orgTreeData.value = toTree(await queryOrgList({ current: !showGlobalData.value }));
  } finally {
    orgTreeLoading.value = false;
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const { content, totalElements } = await queryProductList({
      ...toParams(params.value),
      pageSize: 10,
      pageNum: currentPage.value
    });
    data.value = content;
    total.value = totalElements;
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
  fetchOrg();
});

const handleSort = ({ column, prop, order }: { column: any; prop: string; order: string }) => {
  if (prop) {
    sort.value = (column.sortBy ?? prop) + (order === 'descending' ? '_desc' : '');
  } else {
    sort.value = undefined;
  }
  fetchData();
};
const handleSearch = () => fetchData();
const handleReset = () => {
  table.value.clearSort();
  resetParams(params.value);
  sort.value = undefined;
  fetchData();
};

const handleAdd = () => {
  beanId.value = undefined;
  formVisible.value = true;
};
const handleEdit = (id: number) => {
  beanId.value = id;
  formVisible.value = true;
};
//版本
const handlePermissionEdit = async (id: number) => {
  beanId.value = id;
  dialogVisible.value = true
  const { content } = await productVersionList({
    "filterParams": {
      "productId": beanId.value,
    },
    "pageNum": 1,
    "pageSize": 999,
    "sort": {}
  })
  datav.value = content
};
const versionAdd = async () => {
  versionTitle.value = '新增版本'
  versionVisible.value = true
}
const versionConfirm = async () => {
  versionVisible.value = false
  values.value.productId = beanId.value
  const status = undefined
  if (versionTitle.value === '编辑版本') {
    const { status } = await updateProductVersion(values.value)
  } else {
    const { status } = await createProductVersion(values.value)
  }
   if (status === 0) {
     const { content } = await productVersionList({
      "filterParams": {
        "productId": beanId.value,
      },
      "pageNum": 1,
      "pageSize": 999,
      "sort": {}
    })
    datav.value = content
   }
}
const versionEdit = async (row: object) => {
  versionTitle.value = '编辑版本'
  versionVisible.value = true
  values.value = row
}
const versionDelete = async (id: number) => {
  const {status} = await deleteProductVersion(id)
  if (status === 0) {
    const { content } = await productVersionList({
      "filterParams": {
        "productId": beanId.value,
      },
      "pageNum": 1,
      "pageSize": 999,
      "sort": {}
    })
    datav.value = content
  }
}
const handleDelete = async (ids: number[]) => {
  await deleteProduct(ids);
  fetchData();
  ElMessage.success(t('success'));
};

const handleStatus = async (ids: number[], status: number) => {
  await updateUserStatus(ids, status);
  fetchData();
  ElMessage.success(t('success'));
};

//维护人员
let workerVisible = ref<boolean>(false)
const dataw = ref<Array<any>>([]);
let workerTitle = ref<string>('');
let workerEditVisible = ref<boolean>(false);
const valuew = ref<any>({});

const handleWorkerEdit = async (id: number) => {
  beanId.value = id;
  workerVisible.value = true
  const { content } = await queryProductWorker({
    "filterParams": {
      "productId": beanId.value,
    },
    "pageNum": 1,
    "pageSize": 999,
    "sort": {}
  })
  dataw.value = content
};
const userList = ref<Array<any>>([]);
const workerAdd = async () => {
  workerEditVisible.value = true
  // const { content, totalElements } = await queryUserList({
  //     orgId: org.value?.id,
  //     current: !showGlobalData.value,
  //     Q_OrderBy: sort.value,
  //     page: 1,
  //     pageSize: 999,
  //     Q_NE_type: 5
  //   });
  //   userList.value = content
}
const workerDelete = async (id: number) => {
  const {status} = await deleteProductWorker(id)
  if (status === 0) {
    const { content } = await queryProductWorker({
      "filterParams": {
        "productId": beanId.value,
      },
      "pageNum": 1,
      "pageSize": 999,
      "sort": {}
    })
    dataw.value = content
  }
}
const workerForm = ref<any>({})
const workerConfirm = async () => {
  workerEditVisible.value = false
  workerForm.value.productId = beanId.value
  const { status } = await createProductWorker(workerForm.value)
   if (status === 0) {
     const { content } = await queryProductWorker({
      "filterParams": {
        "productId": beanId.value,
      },
      "pageNum": 1,
      "pageSize": 999,
      "sort": {}
    })
    dataw.value = content
   }
}
</script>
